<template>
  <div class="datapanel">
    <div class="data-panel">
      <div class="panel-header">
        <img
          src="../../assets/more-left.png"
          class="du-prev-y"
          @click="getYear('PRE')"
        />
        <div class="du-prev-m" @click="getPreMonth"></div>
        <div class="du-year-month">
          <span class="sel-year">{{ year }}年</span>
          <span class="sel-month">{{ month + 1 }}月</span>
        </div>
        <div
          src="../../assets/left.png"
          class="du-next-m"
          @click="getNextMonth"
        ></div>
        <img
          src="../../assets/more-left.png"
          class="du-next-y"
          @click="getYear('NEXT')"
        />
      </div>
      <div class="panel-body">
        <table class="calendar-table">
          <thead>
            <tr>
              <td>日</td>
              <td>一</td>
              <td>二</td>
              <td>三</td>
              <td>四</td>
              <td>五</td>
              <td>六</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="row in 6">
              <td
                v-for="col in 7"
                :class="calanderList[row][col].class"
                @click="getSelectDate(calanderList[row][col])"
              >
                <div v-show="calanderList[row][col].showChecked">
                  {{ calanderList[row][col].day }}
                </div>
                <input
                  ref="checkboxRef"
                  class="checkbox-input"
                  v-if="calanderList[row][col].showChecked"
                  type="checkbox"
                  :value="`${year}-${month + 1}-${calanderList[row][col].day}`"
                  v-model="
                    checked[
                      `${year}-${month + 1}-${calanderList[row][col].day}`
                    ]
                  "
                />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="panel-footer">
        <!-- <button type="button" class="du-simple-btn" @click="handleBtn('CLEAR')">
          清空
        </button>
        <button type="button" class="du-simple-btn" @click="handleBtn('NOW')">
          现在
        </button> -->
        <div class="allChecked">
          <span>全选</span>
          <input
            class="allChecked-input"
            ref="allCheckedRef"
            type="checkbox"
            :value="allChecked"
            v-model="allChecked"
            @change="change"
          />
        </div>

        <button
          type="button"
          class="du-simple-btn"
          @click="handleBtn('COMFIRM')"
        >
          确定
        </button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "du-date",
  data() {
    return {
      MonthDays: "",
      trCount: "",
      firstDay: "",
      year: "",
      month: "",
      day: "",
      showCalander: false,
      checked: {},
      allChecked: false,
      allDates: [],
    };
  },
  props: {
    selDate: String,
  },
  created() {
    console.log("this.selDate" + this.selDate);
    this.calendar(this.selDate);
  },
  methods: {
    change() {
      let refs = this.$refs["checkboxRef"];
      this.allDates = [];
      if (!this.allChecked) {
        this.checked = {};
      }
      for (let i = 0; i < refs.length; i++) {
        refs[i].checked = this.allChecked;
        if (this.allChecked) {
          this.checked[refs[i].value] = this.allChecked;
          this.allDates.push(refs[i].value);
          // console.log("allDates==>", this.allDates);
        }
      }
    },
    //是否润年（润年2月份29天）
    isLeapYear(year) {
      return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 1 : 0;
    },
    //根据行列初始化日历返回日期：年、月、日、class
    getCalendarDay(row, col) {
      //row、col从1开始
      var day = (row - 1) * 7 + col - this.firstDay; //日历中的日期天
      var tmp = {};
      if (day <= 0) {
        //日历中上个月的日期-天
        tmp.day = day + this.getPreMonthDay();
        tmp.year = this.month - 1 < 0 ? this.year - 1 : this.year;
        tmp.month = this.month - 1 < 0 ? 11 : this.month;
        tmp.class = "preMonth";
        tmp.showChecked = false;
        return tmp;
      } else if (day > this.dayMonth[this.month]) {
        //日历中下个月的日期-天

        tmp.day = day - this.dayMonth[this.month];
        tmp.year = this.month + 1 > 11 ? this.year + 1 : this.year;
        tmp.month = this.month + 1 > 11 ? 0 : this.month + 1 + 1;
        tmp.class = "nextMonth";
        tmp.showChecked = false;
        return tmp;
      } else {
        tmp.day = day;
        tmp.year = this.year;
        tmp.month = this.month + 1;
        tmp.showChecked = true;
        if (this.day == day) {
          //如果当前天和选择的天一致添加activeDate类
          tmp.class = "curMonth activeDate";
        } else {
          tmp.class = "curMonth";
        }
        return tmp;
      }
    },
    getPreMonthDay() {
      //获取上一个月的天数
      var premonth = this.month - 1;
      if (premonth < 0) {
        //或this.month<1
        return this.dayMonth[11];
      } else {
        return this.dayMonth[premonth];
      }
    },
    getPreMonth() {
      //获取上一个月（包括年）
      var premonth = this.month - 1;
      if (premonth >= 0) {
        this.month = this.month - 1;
      } else {
        this.year--;
        this.month = 11;
      }
      var date = new Date(this.year, this.month, this.day);
      this.calendar(date); //初始化日历
    },
    getNextMonth() {
      var premonth = this.month + 1;
      if (premonth <= 11) {
        this.month = this.month + 1;
      } else {
        this.year++;
        this.month = 1;
      }
      var date = new Date(this.year, this.month, this.day);
      this.calendar(date);
    },
    getYear(v1) {
      if (v1 == "NEXT") {
        this.year++;
      } else if (v1 == "PRE") {
        this.year--;
      }
      var date = new Date(this.year, this.month, this.day);
      this.calendar(date);
    },
    calendar(date) {
      //初始化日历
      var myDate = null;
      if (date) {
        myDate = new Date(date);
      } else {
        myDate = new Date();
      }
      this.year = myDate.getFullYear();
      this.month = myDate.getMonth();
      this.day = myDate.getDate();
      this.monthDays = this.dayMonth[this.month];
      var firstDate = new Date(this.year, this.month, 1);
      this.firstDay = firstDate.getDay(); //当前月的第一天是星期几
    },
    getSelectDate(obj) {
      //选择日期后将日历隐藏并将日期传给父页面
      this.showCalander = false;
      console.log("dateFormat", this.dateFormat(obj.year, obj.month, obj.day));
      this.selDate = this.dateFormat(obj.year, obj.month, obj.day);
      this.$emit("changeDate", this.dateFormat(obj.year, obj.month, obj.day)); //将日期传入父页面
      let refs = this.$refs["checkboxRef"];
      for (let i = 0; i < refs.length; i++) {
        if (!refs[i].checked) {
          this.allChecked = false;
          break;
        }
        this.allChecked = true;
      }
    },
    handleBtn(val) {
      if (val == "CLEAR") {
        //清除按钮
        //            this.selDate=""
        this.$emit("changeDate", ""); //将日期传入父页面
      } else if (val == "NOW") {
        var nowData = new Date();
        this.$emit(
          "changeDate",
          this.dateFormat(
            nowData.getFullYear(),
            nowData.getMonth() + 1,
            nowData.getDate()
          )
        );
      } else if (val == "COMFIRM") {
        console.log("checked", this.checked);
        this.allDates = [];
        Object.keys(this.checked).forEach((item) => {
          if (this.checked[item]) {
            this.allDates.push(item);
          }
        });
        console.log("allDates===>", this.allDates);
        this.showCalander = false;
      }
    },
    showCalanderView() {
      this.showCalander = true;
    },
    dateFormat(year, month, day) {
      return year + "-" + month + "-" + day;
    },
  },
  watch: {
    //监听selDate，selDate改变时重新绘制日历
    selDate: function (date) {
      this.calendar(date);
    },
  },
  computed: {
    selectDate() {
      return `${year}-${month + 1}-${calanderList[row][col].day}`;
    },
    //月份天数数组，放于computed可以缓存，当依赖year改变时才重新计算
    dayMonth: function () {
      return [
        31,
        28 + this.isLeapYear(this.year),
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
      ];
    },
    //将日历的进行缓存
    calanderList: function () {
      var canlanderList = [[], [], [], [], [], [], []];
      for (var row = 1; row <= 6; row++) {
        for (var col = 1; col <= 7; col++) {
          canlanderList[row][col] = this.getCalendarDay(row, col);
        }
      }
      return canlanderList;
    },
  },
};
</script>

<style scoped>
.allChecked {
  display: flex;
  align-items: center;
  margin: 0 10px;
}
.allChecked-input {
  margin: 0 10px;
  width: 25px;
}
.panel-footer {
  display: flex;
  justify-content: flex-end;
}
.du-simple-btn {
  margin: 0 10px;
}
</style>
